import {transPoint,computeAngle,computesLineAllMarker,CUSTOM_COVER_POPUP} from "./utilsHander"
import {drawingStyle} from "./StyleConst"


export default (baidu,
    cover
) => {

    cover = {
        ...cover,
        ...{
            popup:null,
            markers:[],
            polylines:[],
            polygons:[],
            circles:[],
            keyMarkers:{}
        }
    }

    var interval = null;

    /**
     * 添加单个点位
     * @param {longitude 经度,latitude 纬度,event 是否开启事件} marker 
     * @param {*} callBack 回调
     * @returns 
     */
    const createMarker = (marker,callBack) => {
        let {longitude,latitude,event = false,data} = marker
        let {icon,width,height} = marker
        let point = transPoint(Number(longitude), Number(latitude))

        let markerOpt = new BMap.Marker(
            point, 
            { icon:generateIcon(icon,width,height) }
        );

        markerOpt.point_data =  data

        if(event)
        {
            markerOpt.addEventListener("click", (value) => {
                console.log("点位",value);
                callBack(value,marker)
            });
        }
        
        return markerOpt
    }
    

    /**
     * 生成点位图标
     * @param { icon 图片,width , height } data  
     * @returns 
     */
    const generateIcon = (icon,width,height) => {
        let imageSize = null

        if(width && height)
            imageSize = new BMap.Size(width,height)

        return  new BMap.Icon(icon,new BMap.Size(width, height),
            {
                anchor: new BMap.Size(width / 2, height / 2),
                imageOffset: new BMap.Size(0, 0),
                imageSize
            })
    }
    
    
    /**
     * 转换经纬度为百度地图点位数据
     * @param {*} positionArr 
     * @returns 
     */
    const convertToPointArr = (positionArr) => {
        let pointArr = []

        for (let i = 0; i < positionArr.length; i++) {
            let item = positionArr[i]
            
            // console.log("position",item);
            if(item.lng == undefined && item.lat == undefined)
                pointArr.push(transPoint(item.longitude,item.latitude))
            else
                pointArr.push(transPoint(item.lng,item.lat))
        }
        return pointArr;
    }

    /**
     * 添加覆盖物数据  
     * @param {*} type 类型 
     * @param {*} data 覆盖物
     * @param {*} conter 是否居中
     */
    const addCoverData = (type,data,conter) => {
        if(!conter)
        {
            baidu.panTo(conter)
        }

        if(BMAP_DRAWING_MARKER == type)
        {
            cover.markers.push(data)
            baidu.addOverlay(data)
        }
        if(BMAP_DRAWING_POLYLINE == type)
        {
            cover.polylines.push(data)
            baidu.addOverlay(data)
        }
        if(BMAP_DRAWING_POLYGON == type)
        {
            cover.polygons.push(data)
            baidu.addOverlay(data)
        }
        if(CUSTOM_COVER_POPUP == type){
            cover.popup = data
            baidu.addOverlay(data);
        }
    }

    /**
     * 目前只做了点位的分组
     * @param {*} type 点位类型
     * @param {*} group 组名
     * @param {*} key  以data中的某个字段值为唯一值
     * @param {*} data 
     * @returns 
     */
    const addCoverByKey = (type,group,key,marker) => {
        let keyValue = marker.point_data[key]

        if(!cover.keyMarkers[group])  cover.keyMarkers[group] = []

        let markerData = cover.keyMarkers[group]
        
        if(BMAP_DRAWING_MARKER == type)
        {
            let index = markerData.findIndex(m => m.key == keyValue)
            if(index != -1)return

            cover.markers.push(marker)
            markerData.push({
                key:keyValue,
                option:marker
            })

            baidu.addOverlay(marker)
        }
        if(BMAP_DRAWING_POLYLINE == type)
        {

        }
        if(BMAP_DRAWING_POLYGON == type)
        {
           
        }
        if(CUSTOM_COVER_POPUP == type){
         
        }

        console.log("分组数据",cover.keyMarkers);
    }
    
    
    return {
        /** 分组添加点位
         * @param {*} markers 点位集合
         * @param {*} group  组名
         * @param {*} key   唯一主键的属性名
         * @param {*} callBack 
         * @returns 
         */
        loadMarkersKey:(markers,group,key,callBack) => {
            if(markers.length == 0)return

            markers.forEach(item => {
                let marker = createMarker(item,callBack);
                addCoverByKey(BMAP_DRAWING_MARKER,group,key,marker)
            })

        },
        /**
         * 加载多个点位
         * @param {*} markers 
         * @param {*} callBack 
         * @returns 
         */
        loadMarkers:(markers,callBack)=>{
            if(markers.length == 0)return
            
            markers.forEach(item => {
                let marker = createMarker(item,callBack);
                addCoverData(BMAP_DRAWING_MARKER,marker)
            })
           
        },
        /**
         * 动态轨迹(未完成)
         * @param {*} lines 线条集合
         * @param {*} markers 要打点的集合
         * @param {*} callBack 
         * @returns 
         */
        loadDynamiclines:(lines,markers,callBack)=>{
            if(interval){clearInterval(interval)}

            if(lines.length == 0)return

            let pointAll = []
            
            // 计算所有点位
            for(let i in lines)
            {
                i = parseInt(i)
                let item = lines[i]
                let itemNext = lines[i+1]
                if(!itemNext)break

                let point = transPoint(item.longitude,item.latitude)
                // let pointNext = transPoint(itemNext.lng,itemNext.lat)
                // let compResult = computesLineAllMarker(
                //     item.lng,item.lat,itemNext.lng,itemNext.lat,
                //     baidu.getDistance(point,pointNext),
                //     200)
                pointAll = pointAll.concat(point)

                if(callBack)
                    callBack(item)
            }
            
            // let index = 0
            // // 动态线加载
            // interval = setInterval(() => {
            //     let item = pointAll[index]
            //     let itemNext = pointAll[index+1]

            //     if(itemNext == undefined)
            //     {
            //         clearInterval(interval)
            //         return
            //     }
            //     let point = transPoint(item.lng,item.lat)
            //     let pointNext = transPoint(itemNext.lng,itemNext.lat)
            //     let line = new BMap.Polyline([point,pointNext],drawingStyle);
            //     if(index == pointAll.length -2)
            //     {
            //         callBack(markers)
            //     }
            
            //     baidu.centerAndZoom(point, 16);  
            //     addCoverData(BMAP_DRAWING_POLYLINE,line)

            //     index ++
            // },200);

            addCoverData(BMAP_DRAWING_POLYLINE,new BMap.Polyline(pointAll,drawingStyle))
        },
        /**
         * 添加线
         * @param {*} lines 
         * @returns 
         */
        loadPolylines:(lines)=>{
            if(lines.length == 0)return
            
            let line = new BMap.Polyline(convertToPointArr(lines),drawingStyle)
            addCoverData(BMAP_DRAWING_POLYLINE,line)
        },
        /**
         * 添加面
         * @param {*} polygons 
         * @returns 
         */
        loadPolygons:(polygons)=>{
            if(polygons.length == 0)return
            
            let polygon = new BMap.Polygon(convertToPointArr(polygons),drawingStyle)
            addCoverData(BMAP_DRAWING_POLYGON,polygon)
        },
        /**
         * 添加海量点
         * @param {*} markers 
         * @returns 
         */
        loadMassPoint:(markers) => {
            if(markers.length == 0)return

            if (document.createElement('canvas').getContext) {  // 判断当前浏览器是否支持绘制海量点
                var points = [];  // 添加海量点数据
                for (var i = 0; i < markers.length; i++) {
                    let {longitude,latitude}  = markers[i]
                    points.push( transPoint(longitude,latitude) );
                }
                var options = {
                    size: BMAP_POINT_SIZE_SMALL,
                    shape: BMAP_POINT_SHAPE_RHOMBUS,
                    color: 'rgb(72, 105, 255)'
                }
                var pointCollection = new BMap.PointCollection(points, options);  // 初始化PointCollection

                pointCollection.addEventListener('click', function (e) {
                    console.log(e);
                });

                baidu.addOverlay(pointCollection);  
            } else {
                alert('请在chrome、safari、IE8+以上浏览器查看本示例');
            }

        },
        /**
         * 清除方法
         * @param {*} type 点位类型 
         */
        clear:(type) => {
            let {markers,polylines,polygons} = cover
            if(BMAP_DRAWING_MARKER == type)
            {
                markers.forEach(item => {
                    baidu.removeOverlay(item)
                })
                cover.markers = []
            }
            if(BMAP_DRAWING_POLYLINE == type)
            {
                polylines.forEach(item => {
                    baidu.removeOverlay(item)
                })
                cover.polylines = []
            }
            if(BMAP_DRAWING_POLYGON == type)
            {
                polygons.forEach(item => {
                    baidu.removeOverlay(item)
                })
                cover.polygons = []
            }

            if(!type){
                baidu.clearOverlays();
                cover = {
                    popup:null,
                    markers:[],
                    polylines:[],
                    polygons:[],
                    circles:[],

                    keyMarkers:{},
                    keyPolylines:{},
                    keyPolygons:{},
                    keyCircles:{},
                }
            }
        },
        /**
         * 指定移除覆盖物 与addCoverByKey配合使用
         * @param {*} type 
         * @param {*} group 
         * @param {*} keyValue 
         * @returns 
         */
        remove:(type,group,keyValue)=>{
            switch(type)
            {
                case BMAP_DRAWING_MARKER:
                    let groupObj = cover.keyMarkers[group]
                    if(!Array.isArray(groupObj))return console.log("分组获取错误");

                    for (let index = 0; index < groupObj.length; index++) {
                        const element = groupObj[index];

                        if(element.key == keyValue || (element != undefined && keyValue == undefined))
                        {
                            baidu.removeOverlay(element.option)
                            groupObj.splice(index,1)
                            index --;
                        }
                    }
                    
                    break;
                case BMAP_DRAWING_POLYLINE:
            }

        },
        /**
         * 获取覆盖物数据
         * @returns 
         */
        getCoverData(){return cover},
    }
}